/**
 * 性能监控系统 - 用于验证Phase 1优化效果
 * 监控组件渲染性能、数据绑定效率和内存使用情况
 */

// 性能指标接口
interface PerformanceMetrics {
  componentRenders: number;
  dataTransforms: number;
  cacheHits: number;
  cacheMisses: number;
  averageRenderTime: number;
  averageTransformTime: number;
  memoryUsage: number;
  timestamp: number;
}

// 组件性能数据
interface ComponentPerformanceData {
  id: string;
  type: string;
  renderCount: number;
  totalRenderTime: number;
  lastRenderTime: number;
  dataBindingHits: number;
  dataBindingMisses: number;
}

// 性能事件类型
type PerformanceEventType =
  | 'component-render-start'
  | 'component-render-end'
  | 'data-transform-start'
  | 'data-transform-end'
  | 'cache-hit'
  | 'cache-miss'
  | 'batch-update-start'
  | 'batch-update-end';

// 性能事件接口
interface PerformanceEvent {
  type: PerformanceEventType;
  componentId?: string;
  componentType?: string;
  timestamp: number;
  data?: any;
}

/**
 * 性能监控管理器类
 */
export class PerformanceMonitor {
  private enabled: boolean = false;
  private metrics: PerformanceMetrics[] = [];
  private componentData = new Map<string, ComponentPerformanceData>();
  private currentOperations = new Map<string, number>();
  private maxHistorySize = 100; // 最多保存100条历史记录

  constructor(enabled: boolean = false) {
    this.enabled = enabled;
    this.startMemoryMonitoring();
  }

  /**
   * 启用或禁用监控
   */
  setEnabled(enabled: boolean): void {
    this.enabled = enabled;
  }

  /**
   * 记录性能事件
   */
  recordEvent(event: Omit<PerformanceEvent, 'timestamp'>): void {
    if (!this.enabled) return;

    const fullEvent: PerformanceEvent = {
      ...event,
      timestamp: performance.now()
    };

    this.processEvent(fullEvent);
  }

  /**
   * 开始测量组件渲染
   */
  startComponentRender(componentId: string, componentType: string): void {
    if (!this.enabled) return;

    this.recordEvent({
      type: 'component-render-start',
      componentId,
      componentType
    });
  }

  /**
   * 结束测量组件渲染
   */
  endComponentRender(componentId: string, componentType: string): void {
    if (!this.enabled) return;

    this.recordEvent({
      type: 'component-render-end',
      componentId,
      componentType
    });
  }

  /**
   * 开始测量数据转换
   */
  startDataTransform(transformKey: string): void {
    if (!this.enabled) return;

    this.recordEvent({
      type: 'data-transform-start',
      data: { transformKey }
    });
  }

  /**
   * 结束测量数据转换
   */
  endDataTransform(transformKey: string): void {
    if (!this.enabled) return;

    this.recordEvent({
      type: 'data-transform-end',
      data: { transformKey }
    });
  }

  /**
   * 记录缓存命中
   */
  recordCacheHit(cacheKey: string): void {
    if (!this.enabled) return;

    this.recordEvent({
      type: 'cache-hit',
      data: { cacheKey }
    });
  }

  /**
   * 记录缓存未命中
   */
  recordCacheMiss(cacheKey: string): void {
    if (!this.enabled) return;

    this.recordEvent({
      type: 'cache-miss',
      data: { cacheKey }
    });
  }

  /**
   * 处理性能事件
   */
  private processEvent(event: PerformanceEvent): void {
    const { type, componentId, componentType, timestamp } = event;

    switch (type) {
      case 'component-render-start':
        if (componentId) {
          this.currentOperations.set(`render-${componentId}`, timestamp);
        }
        break;

      case 'component-render-end':
        if (componentId && componentType) {
          const startTime = this.currentOperations.get(`render-${componentId}`);
          if (startTime) {
            const renderTime = timestamp - startTime;
            this.updateComponentData(componentId, componentType, renderTime);
            this.currentOperations.delete(`render-${componentId}`);
          }
        }
        break;

      case 'data-transform-start':
        if (event.data?.transformKey) {
          this.currentOperations.set(`transform-${event.data.transformKey}`, timestamp);
        }
        break;

      case 'data-transform-end':
        if (event.data?.transformKey) {
          const startTime = this.currentOperations.get(`transform-${event.data.transformKey}`);
          if (startTime) {
            const transformTime = timestamp - startTime;
            this.recordTransformTime(transformTime);
            this.currentOperations.delete(`transform-${event.data.transformKey}`);
          }
        }
        break;

      case 'cache-hit':
        this.incrementCacheHits();
        break;

      case 'cache-miss':
        this.incrementCacheMisses();
        break;
    }
  }

  /**
   * 更新组件性能数据
   */
  private updateComponentData(
    componentId: string,
    componentType: string,
    renderTime: number
  ): void {
    let data = this.componentData.get(componentId);

    if (!data) {
      data = {
        id: componentId,
        type: componentType,
        renderCount: 0,
        totalRenderTime: 0,
        lastRenderTime: 0,
        dataBindingHits: 0,
        dataBindingMisses: 0
      };
      this.componentData.set(componentId, data);
    }

    data.renderCount++;
    data.totalRenderTime += renderTime;
    data.lastRenderTime = renderTime;
  }

  /**
   * 记录转换时间
   */
  private recordTransformTime(transformTime: number): void {
    // 这里可以累积转换时间统计
  }

  /**
   * 增加缓存命中计数
   */
  private incrementCacheHits(): void {
    // 增加全局缓存命中统计
  }

  /**
   * 增加缓存未命中计数
   */
  private incrementCacheMisses(): void {
    // 增加全局缓存未命中统计
  }

  /**
   * 获取性能报告
   */
  getPerformanceReport(): {
    summary: PerformanceMetrics;
    components: ComponentPerformanceData[];
    recommendations: string[];
  } {
    const components = Array.from(this.componentData.values());

    // 计算总体指标
    const totalRenders = components.reduce((sum, c) => sum + c.renderCount, 0);
    const totalRenderTime = components.reduce((sum, c) => sum + c.totalRenderTime, 0);
    const averageRenderTime = totalRenders > 0 ? totalRenderTime / totalRenders : 0;

    const summary: PerformanceMetrics = {
      componentRenders: totalRenders,
      dataTransforms: 0, // TODO: 实现数据转换统计
      cacheHits: 0, // TODO: 实现缓存统计
      cacheMisses: 0,
      averageRenderTime,
      averageTransformTime: 0,
      memoryUsage: this.getCurrentMemoryUsage(),
      timestamp: Date.now()
    };

    // 生成性能建议
    const recommendations = this.generateRecommendations(components, summary);

    return {
      summary,
      components,
      recommendations
    };
  }

  /**
   * 生成性能优化建议
   */
  private generateRecommendations(
    components: ComponentPerformanceData[],
    summary: PerformanceMetrics
  ): string[] {
    const recommendations: string[] = [];

    // 检查渲染性能
    if (summary.averageRenderTime > 16) {
      recommendations.push('平均渲染时间超过16ms，建议优化组件渲染逻辑');
    }

    // 检查高频渲染组件
    const highRenderComponents = components.filter((c) => c.renderCount > 50);
    if (highRenderComponents.length > 0) {
      recommendations.push(`发现${highRenderComponents.length}个高频渲染组件，建议添加渲染优化`);
    }

    // 检查慢渲染组件
    const slowComponents = components.filter(
      (c) => c.renderCount > 0 && c.totalRenderTime / c.renderCount > 20
    );
    if (slowComponents.length > 0) {
      recommendations.push(`发现${slowComponents.length}个慢渲染组件，建议检查其渲染逻辑`);
    }

    // 内存使用建议
    if (summary.memoryUsage > 100) {
      // 假设100MB为警戒线
      recommendations.push('内存使用量较高，建议检查是否有内存泄漏');
    }

    if (recommendations.length === 0) {
      recommendations.push('性能表现良好，无需特别优化 ✅');
    }

    return recommendations;
  }

  /**
   * 获取当前内存使用量（MB）
   */
  private getCurrentMemoryUsage(): number {
    if ('memory' in performance) {
      return (performance as any).memory.usedJSHeapSize / (1024 * 1024);
    }
    return 0;
  }

  /**
   * 开始内存监控
   */
  private startMemoryMonitoring(): void {
    if (this.enabled && 'memory' in performance) {
      setInterval(() => {
        const memoryUsage = this.getCurrentMemoryUsage();
        if (memoryUsage > 0) {
          // 记录内存使用情况
        }
      }, 10000); // 每10秒检查一次
    }
  }

  /**
   * 清除历史数据
   */
  clearHistory(): void {
    this.metrics = [];
    this.componentData.clear();
    this.currentOperations.clear();
  }

  /**
   * 导出性能数据
   */
  exportData(): string {
    const report = this.getPerformanceReport();
    return JSON.stringify(report, null, 2);
  }
}

// 全局性能监控实例
export const globalPerformanceMonitor = new PerformanceMonitor(
  // 开发环境默认开启
  process.env.NODE_ENV === 'development'
);

// 便捷函数
export const startComponentRender = (componentId: string, componentType: string) => {
  globalPerformanceMonitor.startComponentRender(componentId, componentType);
};

export const endComponentRender = (componentId: string, componentType: string) => {
  globalPerformanceMonitor.endComponentRender(componentId, componentType);
};

export const recordCacheHit = (cacheKey: string) => {
  globalPerformanceMonitor.recordCacheHit(cacheKey);
};

export const recordCacheMiss = (cacheKey: string) => {
  globalPerformanceMonitor.recordCacheMiss(cacheKey);
};

export const getPerformanceReport = () => {
  return globalPerformanceMonitor.getPerformanceReport();
};

// 在window对象上暴露监控工具（仅开发环境）
if (process.env.NODE_ENV === 'development' && typeof window !== 'undefined') {
  (window as any).__performanceMonitor = globalPerformanceMonitor;
}
